<template>
  <div id="myaddress">
    <van-radio-group v-model="radio">
      <van-list
        v-model="loading"
        :finished="finished"
        @load="listRoll"
        :offset="offset"
        :immediate-check="isCheck"
      >
        <div class="line-box" v-for="(item, index) in addressList" :key="index">
          <div class="received-addr">
            <div class="addr-info">
              <div class="font-bold">
                {{ item.name }} &nbsp;&nbsp;{{ item.mobile }}
              </div>
              <div class="text">
                {{ item.province }}{{ item.city }}{{ item.district
                }}{{ item.address }}
              </div>
            </div>
          </div>
          <div class="take-box">
            <div class="take-box-left">
              <!-- 选择使用 -->
              <van-radio
                v-show="lang == 'zh'"
                class="default"
                :name="item.isdefault"
                @click="
                  changeDefault(item.isdefault, index, item.name, item.id)
                "
                >默认地址</van-radio
              >
              <van-radio
                v-show="lang == 'en'"
                class="default"
                :name="item.isdefault"
                @click="
                  changeDefault(item.isdefault, index, item.name, item.id)
                "
                >default</van-radio
              >
            </div>
            <div class="take-box-right">
              <span
                class="edit"
                v-show="lang == 'zh'"
                @click="gotoeditAddress(item.id)"
                ><i></i>编辑</span
              >
              <span
                class="edit"
                v-show="lang == 'en'"
                @click="gotoeditAddress(item.id)"
                ><i></i>edit</span
              >
              <span
                class="del"
                v-show="lang == 'zh'"
                @click="gotodelAddress(item.id)"
                ><i></i>删除</span
              >
              <span
                class="del"
                v-show="lang == 'en'"
                @click="gotodelAddress(item.id)"
                ><i></i>delete</span
              >
            </div>
          </div>
        </div>
      </van-list>
    </van-radio-group>
    <!-- 新增按钮 -->
    <div class="addressBtnBox" @click="gotoshowAddress()">
      <div class="btn" v-show="lang == 'zh'">添加新地址</div>
      <div class="btn" v-show="lang == 'en'">add new address</div>
    </div>
    <div class="nolist" v-show="lang == 'zh'" v-if="dataLength == 0">
      暂无收货地址，快去添加收货地址吧！
    </div>
    <div class="nolist" v-show="lang == 'en'" v-if="dataLength == 0">
      no address in list，go to add ！
    </div>
  </div>
</template>
<script>
import { Toast, List, Loading, RadioGroup, Radio, Dialog } from "vant";
import {
  getMyAddress,
  postDefaultAddress,
  postDelAddress,
} from "@/api/my/userInfo";
export default {
  name: "myaddress",
  //声明组件
  components: {
    [Loading.name]: Loading,
    [Toast.name]: Toast,
    [List.name]: List,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Dialog.name]: Dialog,
  },
  data() {
    return {
      lang: "zh",
      radio: 1, //为1 选中isdefault==1的选项
      pageIndex: 1, //分页页数
      pageSize: 10, //分页条数
      userId: 0, //用户ID
      offset: 50,
      loading: false, //是否正在加载
      finished: false, //是否加载完整
      isCheck: false, //是否一开始检查滚动
      dataLength: 0, //数据listData长度
      isdefault: [], //0非默认地址   1默认地址
      addressList: [], // 收货地址列表
    };
  },
  //实例创建完成后被立即调用
  created() {
    //获取用户ID
    this.getUserId();
    //获取语言环境
    this.getLang();
    //获取地址列表
    this.getList();
  },
  //监听
  watch: {},
  //计算属性
  computed: {},
  //
  methods: {
    //获取用户ID
    getUserId() {
      if (this.$route.query.userId && this.$route.query.userId > 0) {
        this.userId = this.$route.query.userId;
      } else {
        //获取缓存内的用户ID
        this.userId = window.localStorage.getItem("userId");
      }
    },
    //获取语言环境
    getLang() {
      if (this.$route.query.lang) {
        this.lang = this.$route.query.lang;
      }
    },
    //获取地址列表
    getList() {
      getMyAddress(this.userId).then((res) => {
        if (res.code == 200) {
          if (res.data.length > 0) {
            this.addressList = res.data;
            for (let i = 0; i < this.addressList.length; i++) {
              this.addressList[i].isdefault = this.addressList[i].is_default;
            }
            this.loading = false;
            this.finished = true;
          } else {
            //暂无收货地址
            this.loading = false;
            this.finished = true;
          }
          this.dataLength = res.data.length;
        } else {
          Toast(res.msg);
        }
      });
    },
    changeDefault(isdefault, index, name, id) {
      this.radio = 1; //radio会根据点击切换改变成为选择项的name，此处只需要恒选中name=1的选项
      //isdefault为视觉选择标记  获取列表会有延迟  避免用户误解
      for (let i = 0; i < this.addressList.length; i++) {
        this.addressList[i].isdefault = 0;
      }
      //将切换选中的选项标记为1，视觉得知已切换
      this.addressList[index].isdefault = 1;

      console.log("change", isdefault, index, "姓名", name, "ID:", id);
      //调接口   逻辑上切换默认地址状态
      postDefaultAddress(this.userId, id, this.lang).then((res) => {
        if (res.code == 200) {
          if (this.lang == "zh") {
            Toast("切换成功！");
          } else Toast("Change Success！");
          let _this = this;
          setTimeout(function () {
            _this.getList();
          }, 2000);
        } else {
          Toast(res.msg);
        }
      });
    },
    gotoeditAddress(id) {
      //编辑地址跳转
      var title = "";
      if (this.lang == "zh") {
        title = "编辑地址";
      } else {
        title = "Edit Address";
      }
      let para = {};
      para.title = title;
      para.url =
        "/addAddress?userId=" +
        this.userId +
        "&type=2&id=" +
        id +
        "&lang=" +
        this.lang; // type=1新增地址，2编辑地址  id:地址ID
      this.interaction.hLink(para);
    },
    gotodelAddress(id) {
      //删除地址
      var message = "";
      var confirm = "确认";
      var cancel = "删除";
      if (this.lang == "zh") {
        message = "确定将该地址永久删除？";
      } else {
        message = "Are you sure you want to permanently delete this address?";
        confirm = "confirm";
        cancel = "cancel";
      }
      Dialog.confirm({
        title: "",
        message: message,
        confirmButtonText: confirm,
        cancelButtonText: cancel,
      })
        .then(() => {
          // on confirm
          postDelAddress(id, this.lang).then((res) => {
            if (res.code == 200) {
              this.addressList = [];
              this.getList();
            } else {
              Toast(res.msg);
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },
    gotoshowAddress() {
      //新增地址跳转
      var title = "";
      if (this.lang == "zh") {
        title = "新增地址";
      } else {
        title = "Add new Address";
      }
      let para = {};
      para.title = title;
      para.url =
        "/addAddress?userId=" + this.userId + "&type=1" + "&lang=" + this.lang; // type=1新增地址，2编辑地址  id:地址ID
      this.interaction.hLink(para);
    },
    listRoll() {
      //列表滚动加载
      this.pageIndex++;
      this.getList();
    },
  },
};
</script>

<style lang="stylus" scoped>
*{
    box-sizing :border-box;
}
.nolist{
    width :100%;
    height :auto;
    text-align :center;
    font-family: PingFangSC-Regular;
    font-size: 0.373333rem;
    color: #a2a2a2;
    letter-spacing: 0.008rem;
}
.line-box{
    width :100%;
    height :auto ;
    background-color :#ffffff;
    margin-bottom :.266667rem;
}
.received-addr{
    padding: .266667rem;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    .addr-info{
        -webkit-box-flex: 1;
        -webkit-flex: 1;
        flex: 1;
        font-size: .32rem;
        color: #494949;
        .font-bold{
            height :.533333rem;
            line-height :.533333rem;
            width :100%;
            font-weight :bold;
            font-family:PingFangSC-Medium;
            font-size:.373333rem;
            color:#494949;
            letter-spacing:0;
            text-align:left;
        }
        .text{
            position: relative;
            color :#9b9b9b;
            margin-top: .133333rem;
            padding-right: .266667rem;
            height: .906667rem;
            line-height: .453333rem;
            overflow: hidden;
            -o-text-overflow: ellipsis;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            word-break: break-word;
        }
    }
}
.take-box{
    padding: .266667rem;
    border-top  :.026667rem solid #f1f1f1;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    font-size: .373333rem;
    .take-box-left {
        -webkit-box-flex: 1;
        -webkit-flex: 1;
        flex: 1;
        .default {
            color: #cb9c57;
            i {
                background: url("http://img.zuimeng.net.cn/weixuanzhong_dizhi@2x.png") no-repeat;
                background-size: 100%;
                display: inline-block;
                vertical-align: middle;
                width: .426667rem;
                height: .426667rem;
                margin-right: .24rem;
            }
            i.active {
                background: url("http://img.zuimeng.net.cn/xuanzhong_dizhi@2x.png") no-repeat;
                background-size: 100%;
            }
        }
    }
    .take-box-right {
        height: .533333rem;
        line-height: .533333rem;
        -webkit-box-flex: 1;
        -webkit-flex: 1;
        flex: 1;
        text-align: right;
        .edit {
            color: #cb9c57;
        }
         .del {
             margin-left :.8rem;
            color: #eb3148;
        }
    }
}
.addressBtnBox{
    background:#ffffff;
    width:100%;
    height :1.2rem;
    line-height :1.2rem;
    position :fixed;
    bottom :0;
    .btn{
        font-family:PingFangSC-Medium;
        font-size:.4rem;
        color:#cb9c57;
        letter-spacing:.0056rem;
        text-align:center;
    }
}
</style>
<style>
#myaddress .van-radio .van-icon-checked,
#myaddress .van-radio .van-icon-check {
  position: absolute;
  top: 50%;
  margin-top: -0.16rem;
}
#myaddress .van-radio__label {
  margin-left: 0.533333rem !important;
}
</style>
